/*
 * 辅助词
 */

import * as React from 'react';
import { connect } from 'react-redux';
import ReactCustomScrollBars from 'react-custom-scrollbars';
import { Icon, Row, Col, Menu, Spin, message } from 'antd';

import './Index.scss';

import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/assist';

import { fetchAssistList, removeAssist } from 'actions/assist';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadableSearch = LoadableComponent(() => import('pages/knowledge/searchForm'));
const LoadableAssistEdit = LoadableComponent(() => import('./Edit'));
const LoadableCustomPagination = LoadableComponent(() =>
  import('components/common/CustomPagination')
);

interface AssistProps {
  dispatch: (action: any) => any;
  loadingGroup: any;
  assistTotal: number;
  assistList: object[];
}

interface AssistState {
  assistId: any;
  current: number;
  search: any;
}

class AssistList extends React.Component<AssistProps, AssistState> {
  static PAGESIZE = 10;
  static defaultProps: AssistProps = {
    dispatch: () => {},
    loadingGroup: {},
    assistTotal: 0,
    assistList: [],
  };
  constructor(props: AssistProps) {
    super(props);
    this.state = {
      assistId: null,
      current: 1,
      search: null,
    };
  }

  componentDidMount() {
    this.handleFetchAssistList();
  }

  // 分页回调
  onPageChange = (page: number) => {
    const { search } = this.state;

    this.setState({
      current: page,
    });

    let condition: any = {
      page,
    };
    if (search) {
      condition = { ...condition, name: search };
    }

    this.handleFetchAssistList(condition);
  };

  /**
   * 查询Assist列表
   */
  handleFetchAssistList = (
    params: any = {},
    isSearch: boolean = false,
    callback: any = () => {}
  ) => {
    const { current: page } = this.state;
    const pageSize = AssistList.PAGESIZE;

    params = { page, pageSize, ...params };
    if (isSearch) {
      params.page = 1;

      // 记录搜索条件，以便翻页使用
      this.setState({
        current: 1,
        search: params.name || null,
      });
    }
    this.props.dispatch(fetchAssistList(params)).then(callback);
  };

  // 新增回调
  handleNewCallback = (assistId: number) => {
    this.handleFetchAssistList({}, true, () => {
      this.setState({ assistId });
    });
  };

  handleRemoveCallback = () => {
    this.handleFetchAssistList({}, true, () => {
      this.setState({ assistId: null });
    });
  };

  handleEdit = (assistId: any = 0) => {
    this.setState({
      assistId,
    });
  };

  render() {
    const { loadingGroup, assistList, assistTotal } = this.props;
    const { assistId, current } = this.state;

    const paginParams = {
      current,
      total: assistTotal,
      onChange: this.onPageChange,
      simple: true,
      style: {
        float: 'none',
        textAlign: 'center',
      },
    };

    let menuItems = null;

    if (assistList.length) {
      menuItems = (
        <Menu
          mode="inline"
          onSelect={(item: any) => {
            this.handleEdit(item['key']);
          }}
          selectedKeys={[String(assistId)]}>
          {assistList.map((item: any) => {
            return <Menu.Item key={item.id}>{item.name}</Menu.Item>;
          })}
        </Menu>
      );
    } else {
      menuItems = (
        <p className="loading-placeholder">
          <Icon type="frown-o" />
          &nbsp;没有找到辅助词.
        </p>
      );
    }

    return (
      <Row id="panel_content-assist">
        <Col span={6} style={{ marginLeft: -24, marginTop: -23 }}>
          <ReactCustomScrollBars
            id="list_side"
            className="scroll-bar"
            autoHide={true}
            autoHeight={false}
            autoHideTimeout={600}
            autoHideDuration={400}>
            <LoadableSearch
              showAddButton={true}
              handleCreate={this.handleEdit}
              handleSearch={this.handleFetchAssistList}
            />
            <Spin spinning={isLoading(loadingGroup, ACTIONS.FETCH_LIST)}>
              <div className="panel-content">{menuItems}</div>
            </Spin>
            <LoadableCustomPagination {...paginParams} />
          </ReactCustomScrollBars>
        </Col>
        <Col span={18} style={{ marginLeft: 24 }}>
          <div id="edit_side">
            {assistId !== null ? (
              <LoadableAssistEdit
                assistId={assistId}
                handleNewCallback={this.handleNewCallback}
                handleRemoveCallback={this.handleRemoveCallback}
              />
            ) : (
              <p className="loading-placeholder" />
            )}
          </div>
        </Col>
      </Row>
    );
  }
}

function mapStateToProps(state: any) {
  const { assistList, assistTotal } = state.assist;
  const { loadingGroup } = state;

  return {
    loadingGroup,
    assistList,
    assistTotal,
  };
}

export default connect(mapStateToProps)(AssistList);
